﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class PromoAnalysisPro : System.Web.UI.Page
{
    DataColumn cFromNo = new DataColumn("from_no", typeof(string));
    DataColumn cFromNet = new DataColumn("from_net", typeof(string));
    DataColumn cToNo = new DataColumn("to_no", typeof(string));
    DataColumn cToNet = new DataColumn("to_net", typeof(string));
    DataColumn cDate = new DataColumn("date", typeof(DateTime));
    DataColumn cTime = new DataColumn("time", typeof(double));
    DataColumn cHour = new DataColumn("hour", typeof(int));
    DataColumn cMin = new DataColumn("min", typeof(int));



    DataTable callingLog
    {
        get
        {
            if (Session["SESS_CALL_LOG_TABLE"] == null)
            {
                Session["SESS_CALL_LOG_TABLE"] = new DataTable();
                DataTable tb = Session["SESS_CALL_LOG_TABLE"] as DataTable;
                tb.TableName = "CallingLog";
                tb.Columns.Add(cFromNo);
                tb.Columns.Add(cFromNet);
                tb.Columns.Add(cToNo);
                tb.Columns.Add(cToNet);
                tb.Columns.Add(cDate);
                tb.Columns.Add(cTime);
                tb.Columns.Add(cHour);
                tb.Columns.Add(cMin);
            }

            return Session["SESS_CALL_LOG_TABLE"] as DataTable;
        }
        set
        {
            Session["SESS_CALL_LOG_TABLE"] = value;
        }
    }


    Dictionary<string, DateTime> SpecificDateTime
    {
        get
        {
            if (Session["SESS_SPEC_DATE_TIME"] == null)
            {
                Session["SESS_SPEC_DATE_TIME"] = new Dictionary<string, DateTime>();
            }
            return Session["SESS_SPEC_DATE_TIME"] as Dictionary<string, DateTime>;
        }
        set
        {
            Session["SESS_SPEC_DATE_TIME"] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rdoSpecificMonth.Items.Add(new ListItem("All", "0-0"));

            foreach (DateTime dt in SpecificDateTime.Values)
            {
                rdoSpecificMonth.Items.Add(new ListItem(dt.ToString("MMMM") + " " + dt.Year, dt.Year + "-" + dt.Month));
            }

            if (rdoSpecificMonth.Items.Count > 1)
            {
                rdoSpecificMonth.Items[1].Selected = true;
            }
            else if (rdoSpecificMonth.Items.Count > 0)
            {
                rdoSpecificMonth.Items[0].Selected = true;
            }
        }

        AnalysLiteral();

        AnalyseGraph();


    }

    private void AnalysLiteral()
    {
    //    List<DomainUsagePro> usage = new List<DomainUsagePro>();
    //    //----------- ALL ---------------------------------
    //    DomainUsagePro d = 
    //        new DomainUsagePro(callingLog, 
    //                        ProviderEnum.All, 
    //                        UsageDimensionEnum.FREQ,  "");
    //    usage.Add(d);

    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.All,
    //                        UsageDimensionEnum.LONG, "");
    //    usage.Add(d);
    //    //----------- AIS ---------------------------------
    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.AIS,
    //                        UsageDimensionEnum.FREQ, "");
    //    usage.Add(d);

    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.AIS,
    //                        UsageDimensionEnum.LONG, "");
    //    usage.Add(d);
    //    //----------- DTAC ---------------------------------
    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.DTAC,
    //                        UsageDimensionEnum.FREQ, "");
    //    usage.Add(d);

    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.DTAC,
    //                        UsageDimensionEnum.LONG, "");
    //    usage.Add(d);
    //    //----------- TMOVE ---------------------------------
    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.TMOVE,
    //                        UsageDimensionEnum.FREQ, "");
    //    usage.Add(d);

    //    d = new DomainUsagePro(callingLog,
    //                        ProviderEnum.TMOVE,
    //                        UsageDimensionEnum.LONG, "");
    //    usage.Add(d);

    //    foreach (DomainUsagePro u in usage)
    //    {
    //        u.Analysis();
    //    }

    //    usage.Sort();
    //    usage.Reverse();

    //    foreach (DomainUsagePro u in usage)
    //    {
    //        lstSummary.Items.Add(u.ToString());
    //    }
    }

    private void AnalyseGraph()
    {
        cFromNo = callingLog.Columns["from_no"];
        cFromNet = callingLog.Columns["from_net"];
        cToNo = callingLog.Columns["to_no"];
        cToNet = callingLog.Columns["to_net"];
        cDate = callingLog.Columns["date"];
        cTime = callingLog.Columns["time"];
        cHour = callingLog.Columns["hour"];
        cMin = callingLog.Columns["min"];

        string[] yyyy_MM = rdoSpecificMonth.SelectedValue.Split(new char[] { '-' });


        var callingLinq = from myRow in callingLog.AsEnumerable()
                          where (yyyy_MM[0] == "0") ||
                                (myRow.Field<DateTime>(cDate).Year == int.Parse(yyyy_MM[0])) &&
                                (myRow.Field<DateTime>(cDate).Month == int.Parse(yyyy_MM[1]))
                          select new
                          {
                              CallTo = myRow.Field<string>(cToNo),
                              NetTo = myRow.Field<string>(cToNet),
                              OnDate = myRow.Field<DateTime>(cDate),
                              AtTime = myRow.Field<double>(cTime),
                              InHour = myRow.Field<int>(cHour),
                              Minutes = myRow.Field<int>(cMin),
                          };



        var allResults = (from myRow in callingLinq
                          //where (myRow.Field<double>(cTime) > 1 && myRow.Field<double>(cTime) < 2)
                          group myRow by myRow.InHour into grp
                          select new
                          {
                              Id = grp.Key,
                              Count = grp.Count(),
                              Sum = grp.Average(r => r.Minutes)
                          });

        var aisResult = (from myRow in callingLinq
                         where (myRow.NetTo == "ais")
                         group myRow by myRow.InHour into grp
                         select new
                         {
                             Id = grp.Key,
                             Count = grp.Count(),
                             Sum = grp.Average(r => r.Minutes)
                         });

        var dtacResult = (from myRow in callingLinq
                          where (myRow.NetTo == "dtac")
                          group myRow by myRow.InHour into grp
                          select new
                          {
                              Id = grp.Key,
                              Count = grp.Count(),
                              Sum = grp.Average(r => r.Minutes)
                          });
        var tmoveResult = (from myRow in callingLinq
                           where (myRow.NetTo == "tmove")
                           group myRow by myRow.InHour into grp
                           select new
                           {
                               Id = grp.Key,
                               Count = grp.Count(),
                               Sum = grp.Average(r => r.Minutes)
                           });

        var theResult = (from allRow in allResults
                         join ais_i in aisResult on allRow.Id equals ais_i.Id into ais_t
                         join dtac_i in dtacResult on allRow.Id equals dtac_i.Id into dtac_t
                         join tmove_i in tmoveResult on allRow.Id equals tmove_i.Id into tmove_t

                         from aisRow in ais_t.DefaultIfEmpty()
                         from dtacRow in dtac_t.DefaultIfEmpty()
                         from tmoveRow in tmove_t.DefaultIfEmpty()
                         select new
                         {
                             Id = allRow.Id,
                             AllSum = allRow.Sum,
                             AllCount = allRow.Count,
                             DtacSum = dtacRow != null ? dtacRow.Sum : 0,
                             DtacCount = dtacRow != null ? dtacRow.Count : 0,
                             AisSum = aisRow != null ? aisRow.Sum : 0,
                             AisCount = aisRow != null ? aisRow.Count : 0,
                             TmoveSum = tmoveRow != null ? tmoveRow.Sum : 0,
                             TmoveCount = tmoveRow != null ? tmoveRow.Count : 0
                         });

        Chart1.DataSource = theResult;

        Chart1.DataBind();


        //================================================================

        int fromTime = Math.Min(rdoFromHour.SelectedIndex, rdoToHour.SelectedIndex);
        int toTime = Math.Max(rdoFromHour.SelectedIndex, rdoToHour.SelectedIndex);

        var topFriendRaw = (from myRow in callingLinq
                            where (((myRow.NetTo == "tmove") && (chkProvider.Items[2].Selected)) ||
                                  ((myRow.NetTo == "ais") && (chkProvider.Items[0].Selected)) ||
                                  ((myRow.NetTo == "dtac") && (chkProvider.Items[1].Selected)))
                                  &&
                                  ((myRow.InHour >= fromTime) && (myRow.InHour <= toTime))
                            group myRow by myRow.CallTo into grp
                            select new
                            {
                                CallTo = grp.Key,
                                Count = grp.Count(),
                                Sum = grp.Average(r => r.Minutes),
                                Weight = grp.Sum(r => r.Minutes),
                                NetTo = grp.Max(r => r.NetTo)
                            });


        int topCount = rdoTop.SelectedIndex + 1;

        var topFriends = topFriendRaw.Take(topCount);

        switch (rdoBehavior.SelectedIndex)
        {
            case 0: topFriends = topFriendRaw.OrderByDescending(a => a.Weight).Take(topCount); break;
            case 1: topFriends = topFriendRaw.OrderByDescending(a => a.Count).Take(topCount); break;
            case 2: topFriends = topFriendRaw.OrderByDescending(a => a.Sum).Take(topCount); break;
        }


        List<string> tops = new List<string>();
        List<string> nets = new List<string>();
        foreach (var row in topFriends)
        {
            tops.Add(row.CallTo);
            nets.Add(row.NetTo);
        }

        while (tops.Count < 5)
        {
            tops.Add("-");
            nets.Add("-");
        }

        var topCallingLinq = callingLinq.Where(a => a.InHour >= fromTime).Where(b => b.InHour <= toTime);

        var top1 = (from myRow in topCallingLinq
                    where myRow.CallTo == tops[0]
                    group myRow by myRow.InHour into grp
                    select new
                    {
                        Id = grp.Key,
                        Count = grp.Count(),
                        Sum = grp.Average(r => r.Minutes)
                    });

        var top2 = (from myRow in topCallingLinq
                    where myRow.CallTo == tops[1]
                    group myRow by myRow.InHour into grp
                    select new
                    {
                        Id = grp.Key,
                        Count = grp.Count(),
                        Sum = grp.Average(r => r.Minutes)
                    });
        var top3 = (from myRow in topCallingLinq
                    where myRow.CallTo == tops[2]
                    group myRow by myRow.InHour into grp
                    select new
                    {
                        Id = grp.Key,
                        Count = grp.Count(),
                        Sum = grp.Average(r => r.Minutes)
                    });
        var top4 = (from myRow in topCallingLinq
                    where myRow.CallTo == tops[3]
                    group myRow by myRow.InHour into grp
                    select new
                    {
                        Id = grp.Key,
                        Count = grp.Count(),
                        Sum = grp.Average(r => r.Minutes)
                    });
        var top5 = (from myRow in topCallingLinq
                    where myRow.CallTo == tops[4]
                    group myRow by myRow.InHour into grp
                    select new
                    {
                        Id = grp.Key,
                        Count = grp.Count(),
                        Sum = grp.Average(r => r.Minutes)
                    });

        var theTopFriends = (from allRow in allResults
                             join i1 in top1 on allRow.Id equals i1.Id into t1
                             join i2 in top2 on allRow.Id equals i2.Id into t2
                             join i3 in top3 on allRow.Id equals i3.Id into t3
                             join i4 in top4 on allRow.Id equals i4.Id into t4
                             join i5 in top5 on allRow.Id equals i5.Id into t5

                             from r1 in t1.DefaultIfEmpty()
                             from r2 in t2.DefaultIfEmpty()
                             from r3 in t3.DefaultIfEmpty()
                             from r4 in t4.DefaultIfEmpty()
                             from r5 in t5.DefaultIfEmpty()

                             select new
                             {
                                 Id = allRow.Id,

                                 ts1 = r1 != null ? r1.Sum : 0,
                                 tc1 = r1 != null ? r1.Count : 0,

                                 ts2 = r2 != null ? r2.Sum : 0,
                                 tc2 = r2 != null ? r2.Count : 0,

                                 ts3 = r3 != null ? r3.Sum : 0,
                                 tc3 = r3 != null ? r3.Count : 0,

                                 ts4 = r4 != null ? r4.Sum : 0,
                                 tc4 = r4 != null ? r4.Count : 0,

                                 ts5 = r5 != null ? r5.Sum : 0,
                                 tc5 = r5 != null ? r5.Count : 0

                             });

        foreach (var x in theTopFriends)
        {

        }

        Chart2.DataSource = theTopFriends;

        Chart2.Series["ser1"].LegendText = tops[0].Length > 7 ? "1) " + tops[0].Insert(6, "-").Insert(2, "-") + " (" + nets[0] + ")" : "-";
        Chart2.Series["ser2"].LegendText = tops[1].Length > 7 ? "2) " + tops[1].Insert(6, "-").Insert(2, "-") + " (" + nets[1] + ")" : "-";
        Chart2.Series["ser3"].LegendText = tops[2].Length > 7 ? "3) " + tops[2].Insert(6, "-").Insert(2, "-") + " (" + nets[2] + ")" : "-";
        Chart2.Series["ser4"].LegendText = tops[3].Length > 7 ? "4) " + tops[3].Insert(6, "-").Insert(2, "-") + " (" + nets[3] + ")" : "-";
        Chart2.Series["ser5"].LegendText = tops[4].Length > 7 ? "5) " + tops[4].Insert(6, "-").Insert(2, "-") + " (" + nets[4] + ")" : "-";

        Chart2.DataBind();
    }

    protected void btnGetGraph_Click(object sender, EventArgs e)
    {

    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {

    }
}


